#!/usr/bin/python3  
import os  
import time  
import fcntl  
import select  

class SDI12Device:  
    def __init__(self, device_path="/dev/sdi12"):  
        self.device_path = device_path  
        self.fd = None  
        self.timeout = 15  # 默认超时时间15秒  

    def open(self):  
        """打开SDI-12设备"""  
        try:  
            self.fd = os.open(self.device_path, os.O_RDWR)  
            # 设置为非阻塞模式  
            flags = fcntl.fcntl(self.fd, fcntl.F_GETFL)  
            fcntl.fcntl(self.fd, fcntl.F_SETFL, flags | os.O_NONBLOCK)  
            print(f"Successfully opened {self.device_path}")  
            return True  
        except Exception as e:  
            print(f"Failed to open {self.device_path}: {e}")  
            return False  

    def close(self):  
        """关闭SDI-12设备"""  
        if self.fd is not None:  
            os.close(self.fd)  
            self.fd = None  
            print(f"Closed {self.device_path}")  

    def write(self, data):  
        """写入数据到SDI-12设备"""  
        try:  
            bytes_written = os.write(self.fd, data.encode())  
            print(f"Write {bytes_written} bytes: {data}")  
            return bytes_written  
        except Exception as e:  
            print(f"Write error: {e}")  
            return -1  

    def read(self, size=512):  
        """从SDI-12设备读取数据"""  
        try:  
            # 使用select等待数据就绪  
            ready, _, _ = select.select([self.fd], [], [], self.timeout)  
            if not ready:  
                print("Read timeout")  
                return None  

            data = os.read(self.fd, size)  
            if data:  
                # 打印原始数据和十六进制格式  
                print(f"Read {len(data)} bytes: {data}")  
                print(f"Hex data: {' '.join([format(x, '02x') for x in data])}")  
                return data.decode('ascii')  # 使用ASCII解码  
            return None  
        except Exception as e:  
            print(f"Read error: {e}")  
            return None  

    def send_command(self, command):  
        """发送命令并等待响应"""  
        print(f"\nSending command: {command}")  
        if self.write(command) > 0:  
            return self.read()  
        return None  

def main():  
    # 创建SDI12设备实例  
    sdi12 = SDI12Device()  

    try:  
        # 打开设备  
        if not sdi12.open():  
            return  

        # 测试命令列表  
        commands = [  
            "?!",           # 地址查询  
            "AI!",          # 获取传感器信息  
            "AM!",          # 开始测量  
            "AD0!",         # 获取数据 
            "AV!",          # 启动验证
            "AC!",          # 启动并发送测量
        ]  

        # 执行测试命令  
        for cmd in commands:  
            response = sdi12.send_command(cmd)  
            if response:  
                print(f"Response: {response}")  
            else:
                
                
                print("No response or error")  
            time.sleep(1)  # 命令之间的延时  

    except KeyboardInterrupt:  
        print("\nTest interrupted by user")  
    except Exception as e:  
        print(f"Test error: {e}")  
    finally:  
        # 关闭设备  
        sdi12.close()  

if __name__ == "__main__":  
    main()